from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
import json
from django.core import serializers


# 页面list生成工具，输入db返回list，页面page，页面条数limit
def page_util(list, page, limit):
    response = {}
    paginator = Paginator(list, limit)
    response['total'] = paginator.count
    try:
        recycles = paginator.page(page)
    except PageNotAnInteger:
        recycles = paginator.page(1)
    except EmptyPage:
        recycles = paginator.page(paginator.num_pages)
    results = json.loads(serializers.serialize("json", recycles))
    response['list'] = []
    for i in results:
        i['fields']['id'] = i['pk']
        response['list'].append(i['fields'])
    return JsonResponse(response)


# 轻度封装工具
def page_low_util(list, page, limit):
    response = {}
    response['list'] = []
    paginator = Paginator(list, limit)
    response['total'] = paginator.count
    try:
        recycles = paginator.page(page)
    except PageNotAnInteger:
        recycles = paginator.page(1)
    except EmptyPage:
        recycles = paginator.page(paginator.num_pages)
    response['results'] = json.loads(serializers.serialize("json", recycles))
    return response